<template>
  <div class="page page-cart">
    <div v-if="deskNumber" class="header">
      当前桌位号为
      <em>{{deskNumber}}</em>
    </div>
    <a @click="showRecommendList">查看推荐</a>
    <div v-if="showRecommend">
      <van-popup v-model="showRecommend">
        <ul v-if="finalRecommendList.length > 0" class="list-items">
          <li v-for="(item, index) in finalRecommendList" :key="item.id" class="list-item">
            <img :src="'/static/'+item.image" :alt="item.name" v-if="item.image" />
            <img :src="demoImage" :alt="item.name" v-else />
            <span v-text="item.sale+'折'" v-if="item.sale" class="sale"></span>
            <div class="list-info">
              <h4 v-html="item.name"></h4>
              <span v-text="'￥' + formatPrice(item.price, item.sale)" v-if="item.sale" class="price-sale"></span>
              <span v-text="'￥' + item.price" :class="{'line-through': item.sale}" class="price-normal"></span>
              <a @click="addToCart(item, index)">加入菜单</a>
            </div>
          </li>
        </ul>
        <div class="remind" v-else>暂无推荐</div>
      </van-popup>
    </div>
    <div v-if="cartMenuList">
      <van-checkbox-group class="card-goods" v-model="cartMenusIdArray">
        <van-checkbox
          class="card-goods__item"
          v-for="(item, index) in cartMenuList"
          :key="item.id"
          :name="item.id"
          :label-disabled="true"
        >
          <van-card
            :title="item.name"
            :num="item.num"
            :tag="item.sale ? item.sale + '折' : ''"
            :price="item.sale ? formatPrice(item.price, item.sale) : item.price"
            :origin-price="item.sale ? item.price : null"
            :thumb="item.image ? '/static/' + item.image : demoImage"
          >
            <div slot="footer">
              <div class="number">
                <van-button size="mini" @click="decreaseNumber(item.id, index)">-1</van-button>
                {{item.num}}
                <van-button size="mini" @click="increaseNumber(item.id, index)">+1</van-button>
                <van-button size="mini" @click="removeFromCart(item, index)">移出菜单</van-button>
              </div>
            </div>
          </van-card>
        </van-checkbox>
      </van-checkbox-group>
    </div>
    <van-submit-bar
      :price="totalPrice()"
      :disabled="!cartMenuList.length"
      :button-text="submitBarText()"
      @submit="onSubmit()"
    />
  </div>
</template>

<script>
import { mapState } from 'vuex'
import resetMenuList from '@/utils/global'

export default {
  name: 'index',
  data () {
    return {
      demoImage: require('../../../assets/demo.png'),
      deskNumber: null,
      menuArray: [],
      finalMenu: [],
      cartMenuList: [],
      cartMenusIdArray: [],
      recommendMenuList: [],
      finalRecommendList: [],
      showRecommend: false
    }
  },
  computed: mapState(['getDeskInfo', 'getFinalMenu']),
  mounted () {
    if (this.$store.getters.getDeskInfo) {
      this.deskNumber = this.$store.getters.getDeskInfo
    } else {
      return
    }
    this.menuArray = resetMenuList()
    this.getCartInfo()
  },
  methods: {
    submitBarText () {
      let count = this.cartMenusIdArray.length
      return '结算' + (count ? `(${count})` : '')
    },
    getCartInfo () {
      if (this.$store.getters.getFinalMenu.length > 0) {
        this.finalMenu = this.$store.getters.getFinalMenu
      } else {
        return
      }
      if (this.finalMenu.length > 0) {
        let finalMenuArray = [...new Set(this.finalMenu)] // 为了防止意外，一维数组去重复
        this.menuArray.forEach((goods, index) => {
          if (finalMenuArray.indexOf(goods.id) > -1) {
            goods.num = 1 // 加入数量
            this.cartMenuList.push(goods)
            this.cartMenusIdArray.push(goods.id)
          }
        })
      }
      this.submitBarText()
    },
    totalPrice () {
      let arr = this.cartMenuList
      let _this = this
      var sum = arr.reduce(function (prev, cur, index, arr) {
        if (_this.cartMenusIdArray.indexOf(cur.id) > -1) { // 如果不判断，checkbox改变时，总价不变
          if (cur.sale) {
            return prev + Number(cur.price * cur.sale * cur.num / 10)
          } else {
            return prev + Number(cur.price * cur.num)
          }
        } else {
          return prev
        }
      }, 0)
      return sum * 100
    },
    onSubmit () {
      console.log('点击结算')
    },
    formatPrice (price, sale) {
      return Number(price * sale / 10).toFixed(2)
    },
    showRecommendList: function () {
      this.recommendMenuList = [
        ['2', '3'],
        ['2', '4']
      ]
      let recommendMenuArray = [].concat.apply([], this.recommendMenuList) // 组合成一个数组
      let newRecommendMenuArray = [...new Set(recommendMenuArray)] // 一维数组去重复
      let resetRecommendMenuArray = []
      newRecommendMenuArray.forEach((goods, index) => { // 选出不在购物车的数据
        if (this.finalMenu.indexOf(goods) === -1) {
          resetRecommendMenuArray.push(goods)
        }
      })
      this.menuArray.forEach((goods, index) => {
        if (resetRecommendMenuArray.indexOf(goods.id) > -1) {
          this.finalRecommendList.push(goods) // 选出不在购物车的数据之后
        }
      })
      if (this.finalRecommendList.length > 0) {
        this.showRecommend = true
      } else {
        this.showRecommend = false
      }
    },
    resetRecommendData: function () { // 初始化推荐相关数据
      this.recommendMenuList = []
      this.finalRecommendList = []
    },
    addToCart: function (goods, index) {
      goods.num = 1
      this.cartMenuList.push(goods)
      this.cartMenusIdArray.push(goods.id)
      this.finalRecommendList.splice(index, 1)
      this.$store.dispatch('changeFinalMenu', goods.id)
    },
    removeFromCart: function (goods, index) {
      this.$store.dispatch('spliceFinalMenu', index)
      this.cartMenuList.splice(index, 1)
      this.cartMenusIdArray.splice(index, 1)
    },
    decreaseNumber: function (goodsId, index) {
      let currentGoods = this.cartMenuList[index]
      if (currentGoods.num > 1) {
        // this.cartMenuList[index].num = this.cartMenuList[index].num - 1
        currentGoods.num = currentGoods.num - 1
        this.cartMenuList.splice(index, 1, currentGoods)
      } else {
        return false
      }
    },
    increaseNumber: function (goodsId, index) {
      let currentGoods = this.cartMenuList[index]
      currentGoods.num = currentGoods.num + 1
      this.cartMenuList.splice(index, 1, currentGoods)
      // this.cartMenuList[index].num = this.cartMenuList[index].num + 1
    }
  },
  watch: {
    showRecommend: function () {
      if (!this.showRecommend) {
        this.resetRecommendData()
      }
    },
    cartMenuList: function () {
      console.log(this.cartMenuList)
    }
  }
}
</script>

<style scoped lang="less">
  .page-cart{
    padding-bottom: 50px;
  }
  .card-goods__item{
    padding: 10px 15px 10px 35px;
    background-color: #fafafa;
    position: relative;

    /deep/ .van-checkbox__icon {
      position: absolute;
      top: 50%;
      margin-top: -10px;
      left: 15px;
    }

    /deep/ .van-checkbox__label{
      width: 100%;
      margin-left: 15px;
    }
  }
  .card-goods__item.van-checkbox:not(:last-child){
    border-bottom: 1px solid rgba(0, 0, 0, 0.1);
  }
  .van-popup{
    width: 70%;
    border-radius: 5px;
  }

  ul.list-items{
    > li{
      position: relative;
      max-width: 300px;
      margin-bottom: 20px;
      .sale{
        position: absolute;
        right: 0;
        top: 0;
        background-color: #ff0000;
        color: #fff;
        font-style: italic;
        padding: 2px 8px 2px 5px;
        display: block;
      }
      .list-info{
        position: relative;
        margin: 5px 10px 10px;
        padding-right: 80px;
        h4{
          margin-bottom: 10px;
          + span{
            font-size: 16px;
            color: orange;
          }
        }
        .button-function{
          position: absolute;
          right: 0;
          top: 0;
          width: 70px;
          text-align: right;
          button + button {
            margin-top: 2px;
          }
        }
      }
    }
    > li:last-child{
      margin-bottom: 0;
    }
  }
</style>
